package com.lianqi.emcpframework.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program emcp-framework
 * @ClassName WebUtil
 * @description: web工具类，用于获取当前登录用户、请求信息等
 * @author: sky
 * @create: 2018/11/17 22:29
 */
public class WebUtil {

    static final String UNKNOWM = "unknown";
    static final String[] ipHeaders = {
            "X-Forwarded-For",
            "X-Real-IP",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
    };
    /**
     * 获取当前请求的HttpServletRequest实例
     * @return
     */
    public static HttpServletRequest getHttpServletRequest(){
        try {
            return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取请求头map映射
     * @param request 请求
     * @return 请求头Map映射
     */
    public static Map<String,String> getHeaderMapper(HttpServletRequest request){
        Map<String,String> headerMap = new LinkedHashMap<>();
        Enumeration<String>  enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()){
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            headerMap.put(key,value);
        }
        return headerMap;
    }

    /**
     * 获取客户端的真实IP
     * @param request 请求对象
     * @return ip地址
     */
    public static String getIpAddr(HttpServletRequest request){
        for (String ipHeader : ipHeaders){
            String ip = request.getHeader(ipHeader);
            if (!StringUtils.isEmpty(ip) && !ip.contains(UNKNOWM)){
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

}
